package com.manifold.test.config;

import com.lanyine.manifold.mybatis.base.ProviderConfiguration;
import com.lanyine.manifold.mybatis.interceptor.MybatisExcutorInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * MyBatis基础配置
 *
 * @author shadow
 */
@Configuration
@EnableTransactionManagement
@MapperScan("com.manifold.test.**.mapper")
public class MyBatisConfigurer {

    @Resource
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setTypeAliasesPackage("com.manifold.test.**.entity");
        factory.setConfigLocation(new DefaultResourceLoader().getResource("classpath:/mybatis-configuration.xml"));

        // 添加插件
        factory.setPlugins(new Interceptor[]{new MybatisExcutorInterceptor()});
        try {
            return factory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public MapperXmlScan mapperScan() {
        return new MapperXmlScan();
    }

    @Bean
    public ProviderConfiguration providerConfiguration(SqlSessionFactory sqlSessionFactory) {
        return new ProviderConfiguration(sqlSessionFactory);
    }


    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}